<template>
    <view class="content">
        <view class="main-wrap">
            <up-form labelPosition="top" :model="state.model" :rules="state.rules" ref="formRef">
                <up-form-item label="姓名" prop="xueliInfo.fullName" :labelWidth="100" borderBottom ref="item1" required>
                    <up-input v-model="state.model.xueliInfo.fullName" border="none" placeholder="请填写姓名"></up-input>
                </up-form-item>
                <up-form-item label="最高学历" prop="xueliInfo.educationalLevel_text" :labelWidth="85" borderBottom
                    ref="item1" required>
                    <up-input v-model="state.model.xueliInfo.educationalLevel_text" disabled="true"
                        disabledColor="#ffffff" border="none" placeholder="请选择最高学历"></up-input>
                    <template #right>
                        <up-icon name="arrow-right" @click="state.showSheet1=true;"></up-icon>
                    </template>
                </up-form-item>
                <up-form-item label="认证方式" prop="xueliInfo.authType_text" :labelWidth="85" borderBottom ref="item1"
                    required>
                    <up-input v-model="state.model.xueliInfo.authType_text" disabled="true" disabledColor="#ffffff"
                        border="none" placeholder="请选择认证方式"></up-input>
                    <template #right>
                        <up-icon name="arrow-right" @click="state.showSheet2=true;"></up-icon>
                    </template>
                </up-form-item>
                <up-form-item label="学历" prop="xueliInfo.educationTypeId_text" :labelWidth="85" borderBottom ref="item1"
                    required>
                    <up-input v-model="state.model.xueliInfo.educationTypeId_text" disabled="true"
                        disabledColor="#ffffff" border="none" placeholder="请选择学历"></up-input>
                    <template #right>
                        <up-icon name="arrow-right" @click="state.showSheet3=true;"></up-icon>
                    </template>
                </up-form-item>
                <up-form-item label="学校名称" prop="xueliInfo.schoolName" :labelWidth="120" borderBottom ref="item1"
                    required>
                    <up-input v-model="state.model.xueliInfo.schoolName" border="none" placeholder="请填写学校名称"></up-input>
                </up-form-item>
                <up-form-item label="时间段" prop="xueliInfo.startDate" :labelWidth="120" borderBottom ref="item1"
                    required>
                    <view style="display: flex" class="time-wrap">
                        <view @click="openPick(1,$event)">
                            <up-input v-model="state.model.xueliInfo.startDate" disabled="true" disabledColor="#ffffff" border="none" placeholder="开始时间"
                               ></up-input>
                        </view>
                        <up-icon name="arrow-right"></up-icon>
                        <view @click="openPick(2,$event)">
                            <up-input v-model="state.model.xueliInfo.endDate" disabled="true" disabledColor="#ffffff" border="none" placeholder="结束时间"
                                ></up-input>
                        </view>
                    </view>
                </up-form-item>
                <up-form-item label="证书编号" prop="xueliInfo.verifyCode" :labelWidth="120" borderBottom ref="item1"
                    required>
                    <up-input v-model="state.model.xueliInfo.verifyCode" border="none" placeholder="请填写证书编号"></up-input>
                </up-form-item>
                <up-form-item label="证书照片" prop="xueliInfo.image" :labelWidth="120" ref="item1" required>
                    <!-- <up-input v-model="state.model.userInfo.name" border="none"></up-input> -->
                    <up-upload :fileList="state.fileList" @afterRead="afterRead" @delete="deletePic" name="1" multiple
                        :maxCount="1"></up-upload>
                </up-form-item>
            </up-form>
        </view>
        <up-action-sheet :actions="state.actions1" :closeOnClickOverlay="true" :closeOnClickAction="true"
            title="请选择最高学历" cancelText="取消" :show="state.showSheet1" @select="onSelect(1,$event)"
            @close="state.showSheet1=false"></up-action-sheet>
        <up-action-sheet :actions="state.actions2" :closeOnClickOverlay="true" :closeOnClickAction="true"
            title="请选择认证方式" cancelText="取消" :show="state.showSheet2" @select="onSelect(2,$event)"
            @close="state.showSheet2=false"></up-action-sheet>
        <up-action-sheet :actions="state.actions3" :closeOnClickOverlay="true" :closeOnClickAction="true" title="请选择学历"
            cancelText="取消" :show="state.showSheet3" @select="onSelect(3,$event)"
            @close="state.showSheet3=false"></up-action-sheet>

        <up-datetime-picker ref="datetimePickerRef" v-model="state.pickvalue" :show="state.showPick" mode="date"
            :formatter="formatter" @confirm="onPickConfirm" @cancel="state.showPick=false"></up-datetime-picker>
        <!-- <view class="fixed-action-wrap">
            <view class="fixed-action-wrap-button" @click="submit">保存</view>
        </view> -->
    </view>
</template>
<script setup>
// #ifdef MP-WEIXIN
const fs = uni.getFileSystemManager()
// #endif
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import { onReady } from '@dcloudio/uni-app';

const { proxy } = getCurrentInstance()
const datetimePickerRef = ref(null);
// 使用 reactive 创建响应式状态  
const state = reactive({
    fileList: [],
    model: {
        xueliInfo: {
            fullName: "",
            educationalLevel: "", // 最高学历
            educationalLevel_text: "",
            authType: "", // 认证方式
            authType_text: "",
            educationTypeId: "", // 学历
            educationTypeId_text: "",
            schoolName: "", // 学校名称
            startDate: "",
            endDate: "",
            verifyCode: "",
            image: "",
        },
    },
    actions1: [
        { name: '中国大陆学历', id: 0 },
        { name: '港澳台/国际学历', id: 1 }
    ],
    actions2: [
        { name: '毕业证书编号', id: 0 },
        { name: '学信网在线验证', id: 1 }
    ],
    actions3: [],
    rules: {
        'xueliInfo.fullName': {
            type: 'string',
            required: true,
            message: '请填写姓名',
            trigger: ['blur', 'change'],
        },
        'xueliInfo.educationalLevel_text': {
            type: 'string',
            required: true,
            message: '请选择最高学历',
            trigger: ['blur', 'change', 'click'],
        },
        'xueliInfo.authType_text': {
            type: 'string',
            required: true,
            message: '请选择认证方式',
            trigger: ['blur', 'change', 'click'],
        },
        'xueliInfo.educationTypeId_text': {
            type: 'string',
            required: true,
            message: '请选择学历',
            trigger: ['blur', 'change', 'click'],
        },
        'xueliInfo.schoolName': {
            type: 'string',
            required: true,
            message: '请填写学校名称',
            trigger: ['blur', 'change'],
        },
        'xueliInfo.startDate': {
            type: 'string',
            required: true,
            message: '请选择毕业时间段',
            trigger: ['blur', 'change', 'click'],
        },
        'xueliInfo.verifyCode': {
            type: 'string',
            required: true,
            message: '请填写证书编号',
            trigger: ['blur', 'change'],
        },
        'xueliInfo.image': {
            type: 'string',
            required: true,
            message: '请上传证书照片',
            trigger: ['blur', 'change'],
        },
    },
    showSheet1: false,
    showSheet2: false,
    showSheet3: false,
    pickvalue: Date.now(),
    showPick_key: '',
    showPick: false,
});

// 使用 ref 创建响应式引用  
const formRef = ref(null);


async function afterRead(event) {
    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    let lists = [].concat(event.file);
    let fileListLen = state.fileList.length;
    lists.map((item) => {
        state.fileList.push({
            ...item,
            status: 'uploading',
            message: '上传中',
        });
    });
    for (let i = 0; i < lists.length; i++) {
        const result = await uploadFilePromise(lists[i].url);
        let item = state.fileList[fileListLen];
        state.fileList.splice(fileListLen, 1, {
            ...item,
            status: 'success',
            message: '',
            url: result,
        });
        state.model.xueliInfo.image = state.fileList[0].url
        formRef.value.validateField('xueliInfo.image');
        fileListLen++;
    }
}

function onSelect(type, e) {
    state[`showSheet${type}`] = false
    switch (type) {
        case 1:
            state.model.xueliInfo.educationalLevel = e.id
            state.model.xueliInfo.educationalLevel_text = e.name
            formRef.value.validateField('xueliInfo.educationalLevel_text');
            break;
        case 2:
            state.model.xueliInfo.authType = e.id
            state.model.xueliInfo.authType_text = e.name
            formRef.value.validateField('xueliInfo.authType_text');

            break;
        case 3:
            state.model.xueliInfo.educationTypeId = e.id
            state.model.xueliInfo.educationTypeId_text = e.name
            formRef.value.validateField('xueliInfo.educationTypeId_text');
            break;
        default:
            break;
    }
}

function openPick(type) {
    state.showPick = true
    state.showPick_key = type == 1 ? 'startDate' : 'endDate'
}

function onPickConfirm(e) {
    state.showPick = false
    let date = new Date(e.value);

    let formattedDate = `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;

    state.model.xueliInfo[state.showPick_key] = formattedDate
    formRef.value.validateField(`xueliInfo.${state.showPick_key}`);
}
const formatter = (type, value) => {
    if (type === 'year') {
        return `${value}年`;
    }
    if (type === 'month') {
        return `${value}月`;
    }
    if (type === 'day') {
        return `${value}日`;
    }
    return value;
};

function deletePic(event) {
    state.fileList.splice(event.index, 1);
}
function hideKeyboard() {
    uni.hideKeyboard()
}
async function getDictList(){
	const res = await proxy.request('/dict/getList', {dictCode:'educationType'}, {
		method: 'GET'
	})
	state.actions3 = res.data.data.map(item => {
		return {
			name: item.dictName,
			...item
		}
	})
}

function submit() {
    return new Promise((resolve,reject)=>{
        formRef.value?.validate().then(async (valid) => {
        if (valid) {
            const res = await proxy.request('/user/ducation/auth/save', state.model.xueliInfo, {
                methods: 'POST'
            })
            if (res.code == 200) {
                // formRef.value?.resetFields()
                // formRef.value?.clearValidate()
                resolve()
            }

        } else {
            uni.$u.toast('请检查信息是否填写完整')
            reject()
        }
    }).catch(() => {
        // 处理验证错误  
        uni.$u.toast('请检查信息是否填写完整')
        reject()
    });
    })
}

const uploadFilePromise = (url) => {
    return new Promise((resolve, reject) => {
        const base = fs.readFileSync(url, 'base64', 0)
        const basePath = 'data:image/jpeg;base64,' + base

        proxy.request('/common/file/image', { image: basePath }, {
            method: 'POST'
        }).then(res => {
            resolve(res.data.data);
        })

        // console.log(res.data.data)
        // let a = uni.uploadFile({
        //     url: 'http://106.53.65.140:8080/common/file/uploadFile', // 仅为示例，非真实的接口地址
        //     filePath: url,
        //     name: 'file',
        //     formData: {
        //         user: 'test',
        //     },
        //     success: (res) => {
        //         setTimeout(() => {
        //             resolve(res.data.data);
        //         }, 1000);
        //     },
        // });
    });
};

defineExpose({
    submit
})


onReady(() => {
    // 微信小程序需要用此写法
    datetimePickerRef.value.setFormatter(formatter);
})

onMounted(()=>{
    getDictList()
})
</script>
<!-- <style lang="scss">
page {
    background-color: #F5F5F5 !important;
    padding: 32rpx;
    box-sizing: border-box;
}
</style> -->

<style lang="scss" scoped>
.content {
    // padding-bottom: 200rpx;
}

.main-wrap {
    background: #FFFFFF;
    padding: 20rpx 48rpx;
    box-sizing: border-box;
    border-radius: 12rpx 12rpx 12rpx 12rpx;

    .time-wrap {
        ::v-deep input {
            // text-align: center !important;
        }
    }
}

.fixed-action-wrap {
    position: fixed;
    left: 0;
    bottom: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 128rpx;
    padding: 32rpx;
    padding-bottom: env(safe-area-inset-bottom);
    box-sizing: border-box;

    &-button {
        display: flex;
        align-items: center;
        justify-content: center;
        width: calc(100% - 24px);
        height: 80rpx;
        background: #F2CB51;
        border-radius: 58rpx 58rpx 58rpx 58rpx;
    }
}
</style>